package com.platform.eureka.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/** description: http请求
 * @author Hou Dayu 创建时间：2019/8/11
 */
public class HttpService {

	private static Logger logger = LoggerFactory.getLogger(HttpService.class);

	private static Map<String,List<String>> downServers = new ConcurrentHashMap();

	public static Map<String, List<String>> getDownServers() {
		return downServers;
	}

	public static void setDownServers(String key, List<String> value) {
		HttpService.downServers.put(key,value);
	}

	public static String sendGetHttp(String url, Map bodyParams) {
		return sendHttp(url,"get",null,bodyParams);
	}

	public static String sendPostHttp(String url, Map bodyParams) {
		return sendHttp(url,"post",null,bodyParams);
	}

	public static String sendGetHttp(String url, Map bodyParams,Map<String,String> headParams) {
		return sendHttp(url,"get",headParams,bodyParams);
	}

	public static String sendHttp(String url,String method, Map bodyParams,Map<String,String> headParams,Map<String,String> urlParams) {
		if(urlParams != null && !urlParams.isEmpty()){
			StringBuilder sb = new StringBuilder();
			for(String key: urlParams.keySet()){
				sb.append("&"+key+"="+urlParams.get(key));
			}
			if(url.indexOf("?")==-1){
				url = url+"?"+sb.toString().substring(1);
			}else{
				url = url+sb.toString();
			}
		}
		return sendHttp(url,method,headParams,bodyParams);
	}

	public static String sendHttp(String url,String method, String bodyParams,Map<String,String> headParams,Map<String,String> urlParams,String formatType) {
		if(urlParams != null && !urlParams.isEmpty()){
			StringBuilder sb = new StringBuilder();
			for(String key: urlParams.keySet()){
				sb.append("&"+key+"="+urlParams.get(key));
			}
			if(url.indexOf("?")==-1){
				url = url+"?"+sb.toString().substring(1);
			}else{
				url = url+sb.toString();
			}
		}
		return sendHttp(url,method,headParams,bodyParams,formatType);
	}

	public static String sendPostHttp(String url, Map bodyParams,Map<String,String> headParams) {
		return sendHttp(url,"post",headParams,bodyParams);
	}
	public static String sendHttp(String url,String method,Map<String,String> headParams, String bodyParams,String format) {
		CloseableHttpResponse response = null;
		CloseableHttpClient client = null;
		try {
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(500).setSocketTimeout(30000).build();
			if("get".equalsIgnoreCase(method)){
				// 构造请求
				HttpEntityEnclosingRequestBase httpEntity = new HttpEntityEnclosingRequestBase() {
					@Override
					public String getMethod() {
						return "GET";
					}
				};
				if(!isEmpty(headParams) && !headParams.isEmpty()){
					for (Map.Entry<String,String> entry : headParams.entrySet()) {
						httpEntity.setHeader(entry.getKey(), entry.getValue());
					}
				}
				client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
				httpEntity.setURI(URI.create(url));
				if(isNotNull(bodyParams)) {
					if("xml".equalsIgnoreCase(format)){
						httpEntity.setEntity(new StringEntity(bodyParams, ContentType.APPLICATION_XML));
					}else {
						httpEntity.setEntity(new StringEntity(bodyParams, ContentType.APPLICATION_JSON));
					}
				}
				response = client.execute(httpEntity);
			} else {
				// 构造请求
				HttpPost httpEntity = new HttpPost(url);
				client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
				if(!isEmpty(headParams) && !headParams.isEmpty()){
					for (Map.Entry<String,String> entry : headParams.entrySet()) {
						httpEntity.setHeader(entry.getKey(), entry.getValue());
					}
				}
				if(isNotNull(bodyParams)) {
					if("xml".equalsIgnoreCase(format)){
						httpEntity.setEntity(new StringEntity(bodyParams, ContentType.APPLICATION_XML));
					}else {
						httpEntity.setEntity(new StringEntity(bodyParams, ContentType.APPLICATION_JSON));
					}
				}
				response = client.execute(httpEntity);
			}

			if (response != null && response.getStatusLine().getStatusCode() == 200) {
				String line = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
				return line;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("连接失败：",e);
		} finally {
			close(response,client,null);
		}
		return null;
	}
	public static String sendHttp(String url,String method,Map<String,String> headParams, Map bodyParams) {
		return sendHttp(url,method,headParams, JSON.toJSONString(bodyParams),"json");
	}

	private static void close(CloseableHttpResponse response, CloseableHttpClient client, BufferedReader bufferedReader){
		try {
			if(null != bufferedReader){
				bufferedReader.close();
			}
			if (response != null) {
				response.close();
			}
			if(null != client) {
				client.close();
			}
		} catch (IOException e) {
			logger.error("流关闭失败：",e);
		}
	}

	public static boolean isNull(String str) {
		return isEmptyWithTrim(str) || "null".equalsIgnoreCase(str.trim());
	}

	public static boolean isNotNull(String str) {
		return !isNull(str);
	}

	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}

	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	public static boolean isEmptyWithTrim(String str) {
		return isEmpty(str) || "".equals(str.trim());
	}

	public static String doNull(String str) {
		return doNull(str, "").trim();
	}

	public static String doNull(BigDecimal digital) {
		return null != digital ? digital.toString() : "";
	}

	public static String doNull(String str, String with) {
		return isNull(str) ? with : str;
	}

	public static boolean isEmpty(Object obj) {
		return obj == null;
	}

	public static boolean isEmpty(List list) {
		return list == null || list.size() == 0;
	}

	public static boolean isEmpty(Collection collection) {
		return collection == null || collection.isEmpty();
	}
}
